package com.leyou.upload.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;


import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class UploadService {


    private static final List<String> suffiixes= Arrays.asList("image/png","image/jpeg","image/bmp");

    public String uploadImage(MultipartFile file) {
        //校验文件类型
        String type = file.getContentType();
        if (!suffiixes.contains(type)) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        //校验文件内容
        BufferedImage image = null;
        try {
            image = ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        if (image == null) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        //校检通过，进行上传

        //生成保存目录，保存到nginx所在目录下，可以直接通过nginx访问
        File dir = new File("E:\\project\\querycategoryandbrand_04\\nginx-1.12.2\\html\\");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        try {
            //保存图片
            file.transferTo(new File(dir, file.getOriginalFilename()));
            //拼接图片地址
            return "http://image.leyou.com"+file.getOriginalFilename();

        } catch (IOException e) {
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
    }
}
